package com.luge.lib_base

import android.annotation.SuppressLint
import android.content.Context
import androidx.multidex.MultiDexApplication
import com.luge.lib_base.app.ActivityLifecycleCallbacksImpl
import com.luge.lib_base.app.LoadModuleProxy
import kotlinx.coroutines.*
import java.util.ServiceLoader

open class BaseApplication : MultiDexApplication() {

    private val mCoroutineScope by lazy(mode = LazyThreadSafetyMode.NONE) { MainScope() }

    private val mLoadModuleProxy by lazy(mode = LazyThreadSafetyMode.NONE) { LoadModuleProxy() }


    companion object {
        // 全局Context
        @SuppressLint("StaticFieldLeak")
        lateinit var context: Context

        @SuppressLint("StaticFieldLeak")
        lateinit var application: BaseApplication
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        context = base
        application = this
    }

    override fun onCreate() {
        super.onCreate()
        // 全局监听 Activity 生命周期
        registerActivityLifecycleCallbacks(ActivityLifecycleCallbacksImpl())

        // 策略初始化第三方依赖
        initDepends()
    }

    /**
     * 初始化第三方依赖
     */
    private fun initDepends() {
        mCoroutineScope.launch(Dispatchers.Default) {
            mLoadModuleProxy.initByBackstage()
        }

        //log 日志 性能考虑 时间的计算

    }



    override fun onTerminate() {
        super.onTerminate()
        mCoroutineScope.cancel()
    }
}